<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
import { ElMessageBox } from "element-plus";
import type { Action } from "element-plus";
import { useExaminationStore } from "@/stores/examination";
import ExaminationQuestions from "./ExaminationQuestions.vue";
import { formateTimeMS } from "@/utils/utils";

const router = useRouter();
const route = useRoute();

const examinationStore = useExaminationStore();

const typeName = computed(() => {
  if (examinationStore.questionTotal.examTypeId == 1) {
    return "日考";
  } else if (examinationStore.questionTotal.examTypeId == 2) {
    return "周考";
  } else if (examinationStore.questionTotal.examTypeId == 3) {
    return "月考";
  } else {
    return null;
  }
});

const isEdit = ref(false); // 是否答题解析页面
const submitFlag = ref(false); // 辨别是否点击提交按钮，此时不需要弹窗显示是否离开当前页面
const title = ref("开始答题");
// 倒计时
const diff =
  1800 - Math.floor((Date.now() - examinationStore.questionTotal.time) / 1000);
const time = ref(diff);
let timer: any;
onMounted(() => {
  // console.log("路由信息 -- ", route);
  if (route.path === "/answerresult") {
    // 编辑
    isEdit.value = true;
    title.value = "答题解析";
  } else {
    timer = setInterval(() => {
      if (time.value > 1) {
        time.value = time.value - 1;
      } else {
        clearInterval(timer);
        calculateScore();
        ElMessageBox.alert("考试结束", "Title", {
          confirmButtonText: "确认",
          callback: (action: Action) => {
            router.push("/examinationresult");
          },
        });
      }
    }, 1000);
  }
});
onUnmounted(() => {
  clearInterval(timer);
});

const formateTime = computed(() => formateTimeMS(time.value));

const currentQuestionIndex = ref(1); // 当前第几题
const totalQuestionIndex = ref(
  examinationStore.questionTotal.allquestion.length
);

// 获取当前试题
const question = computed(() => {
  console.log(
    "question - - ",
    examinationStore.questionTotal.allquestion[currentQuestionIndex.value - 1]
  );
  return examinationStore.questionTotal.allquestion[
    currentQuestionIndex.value - 1
  ];
});

const questionCorrect = computed(() => {
  if (question.value.type === "单选题") {
    if (
      question.value.answer &&
      question.value.answer.join("") == question.value.correct.join("")
    ) {
      return true;
    } else {
      return false;
    }
  } else if (question.value.type === "多选题") {
    const arr = question.value.answer ? [...question.value.answer] : [];
    if (arr.sort().join("") == question.value.correct.join("")) {
      return true;
    } else {
      return false;
    }
  } else if (question.value.type === "判断题") {
    if (
      question.value.answer &&
      question.value.answer.join("") == question.value.correct.join("")
    ) {
      return true;
    } else {
      return false;
    }
  }
  // console.log(question);
  return 0;
});

// 上一题
const onPrevQuestion = () => {
  currentQuestionIndex.value > 1 &&
    (currentQuestionIndex.value = currentQuestionIndex.value - 1);
};

// 下一题
const onNextQuestion = () => {
  currentQuestionIndex.value < totalQuestionIndex.value &&
    (currentQuestionIndex.value = currentQuestionIndex.value + 1);
};

// 直接跳转某一题
const onJumpQuestion = (index: number) => {
  currentQuestionIndex.value = index;
};

// 答题
const onQuestionChange = (res: any) => {
  // console.log(" - 答题选择结果 -：", res);
  // console.log("当前回答的问题 ", question, question.value.id);
  examinationStore.setAnswer(question.value.id, res);
};

const dialogVisible = ref(false);
// 是否关闭提交试卷的模态框
const handleClose = (done: () => void) => {
  ElMessageBox.confirm("确认关闭当前弹框吗?", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

// 提交试卷，跳转到成绩页面
const submitExaminationHandler = () => {
  submitFlag.value = true;
  dialogVisible.value = false;
  clearInterval(timer);
  calculateScore();
  router.push("/examinationresult");
};

// 计算考试成绩
function calculateScore() {
  // console.log("考试所花时间：", 1800 - time.value);
  examinationStore.setScore();
  examinationStore.setTime(Date.now());
}

// 离开路由之前
onBeforeRouteLeave((to, from, next) => {
  if (isEdit.value) {
    return next(true);
  }
  if (submitFlag.value) {
    return next(true);
  }

  ElMessageBox.confirm("退出当前页面后，会立即结束考试，您确定吗？", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      clearInterval(timer);
      calculateScore();
      next(true);
    })
    .catch(() => {
      next(false);
    });
});
</script>

<template>
  <main>
    <div class="page-header">
      <div class="page-title">
        <p>{{ title }}</p>
      </div>
    </div>
    <div class="page-body">
      <div class="answer-header">
        <ul class="answer-info">
          <li>{{ typeName }}</li>
          <li>{{ question.type }}</li>
          <li>{{ currentQuestionIndex }} / {{ totalQuestionIndex }}</li>
        </ul>
        <div class="answer-time" v-if="!isEdit">剩余时间 {{ formateTime }}</div>
      </div>

      <!-- 题干部分 -->
      <ExaminationQuestions
        :isEdit="isEdit"
        :question="question"
        :questionCorrect="questionCorrect"
        @onChange="onQuestionChange"
      />

      <div class="answer-footer">
        <div class="answer-pagination">
          <el-button
            type="primary"
            size="small"
            class="gxan-btn-on"
            round
            v-if="currentQuestionIndex != 1"
            @click="onPrevQuestion"
            >上一题</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="gxan-btn-on"
            round
            v-if="currentQuestionIndex != totalQuestionIndex"
            @click="onNextQuestion"
            >下一题</el-button
          >
          <el-button
            type="primary"
            size="small"
            class="gxan-btn-on"
            round
            v-if="currentQuestionIndex === totalQuestionIndex && !isEdit"
            @click="dialogVisible = true"
            >提交试卷</el-button
          >
        </div>
        <div class="all-answer">
          <p>开始答题</p>
          <ul class="current-answer-list">
            <li
              v-for="(item, index) in examinationStore.questionTotal
                .allquestion"
              :key="index"
              :class="{
                cur_question: index + 1 == currentQuestionIndex,
                wrong_question: isEdit,
                right_question:
                  isEdit &&
                  item.answer &&
                  item.answer.sort().join('') == item.correct.join(''),
              }"
              @click="onJumpQuestion(index + 1)"
            >
              {{ index + 1 }}
            </li>
          </ul>
        </div>
      </div>
    </div>
  </main>

  <el-dialog
    v-model="dialogVisible"
    align-center
    :show-close="false"
    width="60%"
  >
    <p>交卷即可查看试卷全部答案及解析，是否立即交卷</p>
    <template #footer>
      <div class="answer-dialog-footer">
        <el-button type="primary" @click="submitExaminationHandler"
          >确认交卷</el-button
        >
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss">
@import "@/assets/scss/global.scss";

.answer-header {
  display: flex;
  justify-content: space-between;

  .answer-info {
    display: flex;

    li {
      height: 20px;
      line-height: 20px;
      padding: 0 10px;
      border: 1px solid #ddd;
      border-radius: 2px;
      margin-right: 20px;
      font-size: 12px;
    }
  }

  .answer-time {
    color: $color-theme;
  }
}

.answer-footer {
  padding: 20px 0;

  .answer-pagination {
    display: flex;
    justify-content: flex-end;
  }

  .all-answer {
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #ddd;

    .current-answer-list {
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;

      li {
        width: 20px;
        height: 20px;
        text-align: center;
        line-height: 20px;

        margin-right: 10px;
        margin-bottom: 10px;

        cursor: default;
        user-select: none;
        color: #666;
        border: 1px solid #666;
        background-color: #fff;
      }
      .wrong_question {
        background-color: $color-error;
        color: #fff;
        border: none;
      }
      .right_question {
        color: #666;
        border: 1px solid #666;
        background-color: #fff;
      }
      .cur_question {
        background-color: $color-theme;
        color: #fff;
        border: none;
      }
    }
  }
}

.answer-dialog {
  p {
    font-size: 22px;
    font-weight: 500;
    text-align: center;
    padding: 60px 0;
  }

  .answer-dialog-footer {
    display: flex;
    justify-content: center;

    button {
      margin: 0 20px;
    }
  }
}
</style>
